import { Component, OnInit } from '@angular/core';
import { InterceptorService } from '../../../../share/interceptor.service';
import { NzMessageService } from 'ng-zorro-antd';
// import { UploadFile } from '';
import { FileUploader } from 'ng2-file-upload'; // 上传文件支持库
import { LandScapeEntity } from '../../../../models/land-scape-entity';
// 删除确认弹框
import { ConfirmationService } from 'primeng/primeng';
import { PersonalInfoEntity } from 'app/models/personal-info-entity';

@Component({
  selector: 'app-add-landscape',
  templateUrl: './add-landscape.component.html',
  styleUrls: ['./add-landscape.component.css']
})
export class AddLandscapeComponent implements OnInit {

  constructor(
    private http: InterceptorService,
    private msg: NzMessageService,
    private confirmationService: ConfirmationService
  ) { }

  ngOnInit() {
    this.getData();
    this.getProvince();
  }

  landScape: LandScapeEntity = new LandScapeEntity();
  personInfo: PersonalInfoEntity = new PersonalInfoEntity();
  provinceOptions: string[]; // 省
  cityOptions: string[]; // 市
  countyOrDistrictOptions: String[]; // 县/区

  // 表格数据
  btnAdd = true;
  btnDelete = true;
  btnEdit = false;
  btnImport = false;
  btnExport = false;
  title = ['风景名称', '描述', '地址', '备注'];
  arrbutes = ["name", "description", 'address', 'remark'];
  btnList: string[] = ["编辑"];
  paging = true;
  pageSize = 10;
  page = 1;
  sizeList = [5, 10, 15, 50];
  addInfo: any = new Array();
  arr = new Array();
  btnstyle = [
    { "color": "blue" }]
  total: number;
  data = new Array();
  isCheck = true;

  userId: string = 'YtH67q6ykRmfH5F6Re2Fb';

  /**
   * 风景页面加载数据
   */
  getData() {
    let url = 'graduate-web/landScape/selectLandScape/' + this.userId + '/' + this.page + '/' + this.pageSize;
    this.http.get(url).subscribe(
      res => {
        if (res.json().code == '0000') {
          this.data = res.json().data.list;
          this.total = res.json().data.total;
          console.log("======================风景信息==========================");
          console.log(this.data);
        }
      }
    );
  }

  //打开添加模态框
  addOpen(el: HTMLElement, addModal: HTMLElement) {

    addModal.style.visibility = 'visible';
    document.getElementById('name').focus();

  }

  // 提示框
  display: boolean = false;
  messages: '';

  /**
   * 提示框
   */
  showDialog(string) {
    this.messages = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);
  }

  /**
    * 自定义操作列
    */
  operatData(obj: any, editModal: HTMLElement) {
    switch (obj.element.innerText) {
      case '编辑':
        this.editOpen(obj.data, editModal);
        break;
      default:
        break;
    }
  }

  // 打开修改模态框
  editOpen(index: any, editModal: HTMLElement) {
    editModal.style.visibility = 'visible';
    // this.homeInfo.familyMemName = this.data[index].familyMemName;
    // this.homeInfo.relationshipId = this.data[index].relationshipId;
    this.landScape.name = this.data[index].name;
    this.landScape.remark = this.data[index].remark;
    this.landScape.description = this.data[index].description;
     this.landScape.id = this.data[index].id;
    this.landScape.address = this.data[index].address;
    // this.landScape.regionId = this.data[index].regionId;

    document.getElementById('name').focus();
  }

  // 关闭模态框
  close(modal: HTMLElement) {
    modal.style.visibility = 'hidden';
    this.landScape = new LandScapeEntity();
  }

  //添加风景
  doAdd(addModal: HTMLElement) {
    let addUrl = 'graduate-web/landScape/addLandScape/';

    this.landScape.userId = this.userId;
    let body = JSON.stringify(this.landScape);
    this.http.post(addUrl, body).toPromise().then(
      res => {
        this.showDialog(res.json().message);
        this.getData();//回显
        this.close(addModal);
        console.log(res.json().message + '！！！！！');
      }
    );
  }
  //修改风景
  doUpdate(editModel: HTMLElement) {
    let editUrl = 'graduate-web/landScape/updateLandSpace/';
    let userId = localStorage.getItem('userId');
    this.landScape.userId = this.userId;
    
    console.log('------------------------风景实体-------------------------');
    console.log(this.landScape);
    let body = JSON.stringify(this.landScape);
    this.http.post(editUrl, body).toPromise().then(
      res => {
        console.log(res.json().code);
         if(res.json().code=='0000'){
          this.showDialog(res.json().message);
          this.getData();//回显
          this.close(editModel);
          console.log(res.json().message + '！！！！！');
        }
      }
    );
  }
  //删除风景
  deleteDatas(el: any) {

    let operator = '徐玲博-假数据';
    this.confirmationService.confirm({
      message: '你确定删除景点吗？',
      accept: () => {
        // let obj = [];
        // for (let i = 0; i < el.length; i++) {
        //   let landscapeEntity = new LandScapeEntity();
        //   landscapeEntity.userId = this.data[el[i]].userId;
        //   landscapeEntity.operator = operator;
        //   obj.push(landscapeEntity);
        // }
        // let deleteUrl = 'graduate-web/homeInfo/deleteLand';

        let obj = [];
        for (let i = 0; i < el.length; i++) {

          let id = this.data[el[i]].id;
          obj.push(id);
        }

        console.log('----------------------------打印批量删除ids-----------------------------');
        console.log(obj);
        let deleteUrl = 'graduate-web/landScape/deleteLand/' + operator;

        let body = JSON.stringify(obj);
        this.http.post(deleteUrl, body).subscribe(
          res => {
            if (res.json().code != null && res.json().code == '0000') {
              this.showDialog(res.json().message);
              this.getData();
              this.total--;
            } else {
              this.showDialog(res.json().message);
              this.getData();
            }
          }
        );
        // }
      }
    });
  }

  // -------------------------------------------住址START--------------------------------------------
  //获得省
  getProvince() {
    let proviceUrl = "graduate-web/administrativeRegion/selectProvince";
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.provinceOptions = res.json().data;
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "37",
              name: "河北"
            }
          ];
          this.provinceOptions = data;
        }
        console.log("返回值code" + res.json().code + "省返回值" + this.provinceOptions);
      }
    );
  }

  // 改变住址省，触发查询市
  changeProvince(ProvinceId: string) {
    this.getCity(ProvinceId);
    console.log(ProvinceId);
  }


  // 获得市
  getCity(provinceId) {
    // provinceId = "37";
    // 方案1-后端方法
    let cityUrl = "graduate-web/administrativeRegion/selectSubRegionById/" + provinceId;
    console.log(provinceId + "省参数");
    this.http.get(cityUrl).subscribe(
      res => {
        if (res.json().code = "0000") {
          this.cityOptions = res.json().data;
          console.log(this.cityOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "38",
              pid: "37",
              name: "石家庄"
            }, {
              id: "124",
              pid: "37",
              name: "保定"
            }, {
              id: "197",
              pid: "37",
              name: "廊坊"
            }, {
              id: "150",
              pid: "37",
              name: "张家口"
            }, {
              id: "84",
              pid: "37",
              name: "邯郸"
            }
          ];
          this.cityOptions = data;
        }
      }
    );
  }


  // 改变住址市，触发改变县区
  changeCity(cityId: string) {
    this.getCountyOrDistrict(cityId);
  }
  // 获得县/区
  getCountyOrDistrict(cityId) {
    // cityId = "38";
    // 方案1-后端方法
    let countyOrDistrictUrl = "graduate-web/administrativeRegion/selectSubRegionById/" + cityId;
    this.http.get(countyOrDistrictUrl).subscribe(
      res => {
        if (res.json().code == "0000") {
          this.countyOrDistrictOptions = res.json().data;
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "48",
              pid: "38",
              name: "正定县"
            }, {
              id: "203",
              pid: "197",
              name: "大城县"
            }, {
              id: "55",
              pid: "38",
              name: "平山县"
            }, {
              id: "199",
              pid: "197",
              name: "广阳区"
            }, {
              id: "198",
              pid: "197",
              name: "安次区"
            }, {
              id: "43",
              pid: "38",
              name: "裕华区"
            }, {
              id: "39",
              pid: "38",
              name: "长安区"
            }
          ];
          this.countyOrDistrictOptions = data;
        }
      }
    );
  }
  // ------------------------------------------住址END-------------------------------------

  // 上传图片
  handleChange({ file, fileList }) {
    const status = file.status;
    if (status !== 'uploading') {
      console.log(file, fileList);
    }
    if (status === 'done') {
      this.msg.success(`${file.name} 文件上传成功.`);
    } else if (status === 'error') {
      this.msg.error(`${file.name} 文件上传失败.`);
    }
  }

  /**
   *modal框可拖拽
  */
  draggable() {
    $('.modal-dialog').draggable();
  }

}
